<template>
    <div class="samples">
        <div class="radius"
            :style="{ borderRadius: `var(--el-border-radius-base)`, boxShadow: `var(--el-box-shadow-dark)` }">
            <div class="samples-header">
                <el-form :model="form">
                    <el-row>
                        <el-form-item>
                            <el-input v-model="form.key" size="small" clearable style="width: 210px;"
                                placeholder="样本编码/类型/姓名/身份证号" />
                        </el-form-item>
                        <el-form-item>
                            <el-dropdown split-button size="small" style="margin-right: 3px;" @click="search">
                                查询
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="advancedSearch">高级查询</el-dropdown-item>
                                        <el-dropdown-item @click="resetSearch">重置查询</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            <el-button type="primary" size="small" @click="log">采集录入</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" :disabled="!state"
                                @click="underReview(null)"><el-icon>
                                    <FolderAdd />
                                </el-icon>审核入库</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" :disabled="removeId.length === 0"
                                @click="stockRemove"><el-icon>
                                    <FolderRemove />
                                </el-icon>出库</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="exportXlsx">导出EXCEL</el-button>
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
            <div class="table-container">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column fixed type="selection" width="55" />
                    <el-table-column prop="sampleCode" label="样本编码" />
                    <el-table-column prop="sourceName" label="姓名" />
                    <el-table-column prop="collectAddressName" label="采集地点" />
                    <el-table-column label="采集时间" width="140">
                        <template #default="scope">
                            {{ scope.row.receiveDate.substring(0, 10) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="性别">
                        <template #default="scope">
                            <span v-if="scope.row.sex == 1">男</span>
                            <span v-if="scope.row.sex == 2">女</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="idCard" label="身份证号" width="180" />
                    <el-table-column prop="age" label="年龄" />
                    <el-table-column prop="telephone" label="联系电话" width="120" />
                    <el-table-column label="是否怀孕">
                        <template #default="scope">
                            <span v-if="scope.row.pregnant == 0">否</span>
                            <span v-if="scope.row.pregnant == 1" style="color:#CD5C5C">是</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gestWeek" label="孕周" />
                    <el-table-column prop="homeAddress" label="家庭地址" width="200" />
                    <el-table-column prop="applyUser" label="录入人员" width="140" />
                    <el-table-column prop="createOn" label="录入时间" width="180" />
                    <el-table-column prop="createBy" label="审核人" width="140" />
                    <el-table-column prop="sampleTypeName" label="样本类型" />
                    <el-table-column label="库存状态">
                        <template #default="scope">
                            <span v-if="scope.row.state == 1" style="color:#0BB2D4">入库</span>
                            <span v-if="scope.row.state == 2">出库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" show-overflow-tooltip label="备注" />
                    <el-table-column fixed="right" label="状态" width="60">
                        <template #default="scope">
                            <span v-if="scope.row.status == 2" style="color:#008000">入审</span>
                            <span v-if="scope.row.status == 1" style="color:#00FF00">入审</span>
                            <el-button v-if="scope.row.status == 0" size="default" link
                                @click="underReview(scope.row.id)">未审</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="90">
                        <template #default="scope">
                            <div style="display: flex; justify-content: flex-start;">
                                <el-button size="mini" type='primary' link
                                    @click="editSamples(scope.row.id)">修改</el-button>
                                <el-button v-if="scope.row.status == 0" size="mini" type="scuccess"
                                    style="margin-left: 8px; color: #20B6A7;" link
                                    @click="deleteSamples(scope.row.id)">删除</el-button>
                                <el-button v-else size="mini" type="info" disabled style="margin-left: 8px;"
                                    link>删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="pagination">
                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-size="pageSize" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]"
                    @size-change="handleSizeChange" @current-change="handlePageChange" />
            </div>
        </div>
    </div>
    <!-- 高级查询 -->
    <el-dialog v-model="dialogFormVisible" title='高级查询' width="50%">
        <el-form ref="ruleFormRef" style="width: 100%;" :model="form">
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="样本编码" :label-width="formLabelWidth">
                        <el-input v-model="form.sampleCode" size="small" placeholder="样本编码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="类型名称" :label-width="formLabelWidth">
                        <el-input v-model="form.sampleTypeName" size="small" placeholder="类型名称"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="采集时间" :label-width="formLabelWidth">
                        <el-date-picker v-model="form.receiveDateStart" type="date" placeholder="开始时间" size="small"
                            format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            style="width: 120px;" />-&nbsp;&nbsp;<el-date-picker v-model="form.receiveDateEnd"
                            type="date" placeholder="结束时间" size="small" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            style="width: 123px;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="录入时间" :label-width="formLabelWidth">
                        <el-date-picker v-model="form.createOnStart" type="date" placeholder="开始时间" size="small"
                            format="YYYY/MM/DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss"
                            style="width: 120px;" />-&nbsp;&nbsp;<el-date-picker v-model="form.createOnEnd" type="date"
                            placeholder="结束时间" size="small" format="YYYY/MM/DD hh:mm:ss"
                            value-format="YYYY-MM-DD hh:mm:ss" style="width: 123px;" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="年龄范围" :label-width="formLabelWidth">
                        <el-input v-model="form.ageStart" size='small' style="width: 120px" placeholder="开始年龄" />
                        -&nbsp;&nbsp;<el-input v-model="form.ageEnd" size='small' style="width: 123px"
                            placeholder="结束年龄" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="姓名" :label-width="formLabelWidth">
                        <el-input v-model="form.sourceName" size='small' placeholder="姓名" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-select v-model="form.sex" placeholder="性别" size="small" style="width: 100%;">
                            <el-option label="男" value="1"></el-option>
                            <el-option label="女" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="采集地点" :label-width="formLabelWidth">
                        <el-input v-model="form.collectAddressName" size='small' placeholder=" 采集地点" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="身份证号" :label-width="formLabelWidth">
                        <el-input v-model="form.sourceIdCard" size='small' placeholder="身份证号" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" :label-width="formLabelWidth">
                        <el-input v-model="form.telephone" size='small' placeholder="联系电话" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="库存状态" :label-width="formLabelWidth">
                        <el-select v-model="form.state" placeholder="库存状态" size="small" style="width: 100%;">
                            <el-option label="入库" value="1"></el-option>
                            <el-option label="出库" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item class="submit">
                <el-button @click="resetSearch">重置</el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    查询
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 采集录入/修改 -->
    <el-dialog v-model="dialogFormVisibleAddUp" :title=title width="50%">
        <el-form ref="ruleFormRefAddEdit" :model="ruleForm" :rules="rules">
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="样本编码" :label-width="RuleFormLabelWidth" prop="sampleCode">
                        <el-input v-model="ruleForm.sampleCode" placeholder="样本编码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="样本类型" :label-width="RuleFormLabelWidth" prop="sampleTypeName">
                        <el-select v-model="ruleForm.sampleTypeName" placeholder="请选择" style="width: 100%;"
                            @change="getSample">
                            <el-option v-for="item in optionType" :key="item.id" :label="item.name" :value="item.id">
                                <span style="float: left">{{ item.name }}</span>
                                <span style="float: right; color: rgb(132, 146, 166); font-size: 13px;">
                                    <img :src="item.photo" style="width: 20px; height: 20px;" />
                                </span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="身份证号" :label-width="RuleFormLabelWidth" prop="idCard">
                        <el-input v-model="ruleForm.idCard" @blur="getIdCard" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="姓名" :label-width="RuleFormLabelWidth" prop="sourceName">
                        <el-input v-model="ruleForm.sourceName" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="RuleFormLabelWidth" prop="sex">
                        <el-radio-group v-model="ruleForm.sex">
                            <el-radio :label=1>男</el-radio>
                            <el-radio :label=2>女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="年龄" :label-width="RuleFormLabelWidth" prop="age">
                        <el-input-number v-model="ruleForm.age" :min="0" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="联系电话" :label-width="RuleFormLabelWidth">
                        <el-input v-model="ruleForm.telephone" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="家住地址" :label-width="RuleFormLabelWidth">
                        <el-input v-model="ruleForm.homeAddress" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="8">
                <el-col :span="12">
                    <el-form-item label="采集时间" :label-width="RuleFormLabelWidth" prop="receiveDate" class="receiveDate">
                        <el-date-picker v-model="ruleForm.receiveDate" type="date" placeholder="选择日期时间"
                            format="YYYY/MM/DD" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="采集地点" :label-width="RuleFormLabelWidth" prop="collectAddressName">
                        <el-select v-model="ruleForm.collectAddressName" value-key="itemValue" placeholder="采集地点"
                            style="width: 100%;" @change="handleChangeAddress">
                            <el-option v-for="item in optionAddress" :key="item.itemValue" :label="item.itemName"
                                :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="是否怀孕" prop="pregnant" :label-width="RuleFormLabelWidth">
                    <el-radio-group v-model="ruleForm.pregnant">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-row>
            <el-form-item label="备注" :label-width="RuleFormLabelWidth">
                <el-input v-model="ruleForm.remark" type="textarea" style="width: 100%; height: 51px;" />
            </el-form-item>
            <el-form-item class="submit" style="margin-top: 40px;">
                <el-button type="success" @click="submitFormAddAndEdit(ruleFormRefAddEdit)">
                    确定
                </el-button>
                <el-button @click="resetFormAddAndUpdate(ruleFormRefAddEdit)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    getSampesList, getSampesAddress, getSampesType, saveSamples,
    getSampesByCreator, getSampesReview, sampeswDelete, sampesRemove,
    getIdSamples, exportSamples, getSampletype, getIdCardDetail
} from '@/api/biosample-samples'
import { onMounted, reactive, ref, nextTick } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

const t = Date.now()
interface from {
    sampleCode: string
    sampleTypeName: string
    collectAddressName: string
    receiveDateStart: string
    receiveDateEnd: string
    createOnStart: string
    createOnEnd: string
    ageStart: string
    ageEnd: string
    state: string
    sex: string
    sourceName: string
    sourceIdCard: string
    telephone: string
    key: any
    page: number
    limit: number
}
const pageSize = ref(10)
const currentPage = ref(1)
const form = reactive<from>({
    sampleCode: '',
    sampleTypeName: '',
    collectAddressName: '',
    receiveDateStart: '',
    receiveDateEnd: '',
    createOnStart: '',
    createOnEnd: '',
    ageStart: '',
    ageEnd: '',
    state: '',
    sex: '',
    sourceName: '',
    receiveDateStart: '',
    receiveDateEnd: '',
    createOnStart: '',
    createOnEnd: '',
    ageStart: '',
    ageEnd: '',
    state: '',
    sex: '',
    sourceName: '',
    sourceIdCard: '',
    telephone: '',
    key: null,
    page: 1,
    limit: 10,
    key: null,
    page: 1,
    limit: 10,
})

const title = ref('样本采集录入')
const ruleFormRef = ref<FormInstance>()
const title = ref('样本采集录入')
const ruleFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const dialogFormVisibleAddUp = ref(false)
const tableData = ref([])
const delId = ref([])
const dialogFormVisibleAddUp = ref(false)
const tableData = ref([])
const delId = ref([])
const total = ref(0)
const formLabelWidth = '100px'
const RuleFormLabelWidth = '90px'
const optionAddress = ref([])
const optionType = ref([])
const state = ref()
const removeId = ref([])

interface RuleForm {
    sampleCode: string
    sampleTypeName: number
    idCard: string
    sourceName: string
    sex: number
    age: number
    telephone: string
    homeAddress: string
    receiveDate: string
    collectAddressName: any
    pregnant: number
    remark: string
}
const ruleFormRefAddEdit = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    sampleCode: '',
    sampleTypeName: 106,
    idCard: '',
    sourceName: '',
    sex: 1,
    telephone: '',
    homeAddress: '',
    receiveDate: getCurrentDate(),
    collectAddressName: null,
    age: 0,
    pregnant: 0,
    remark: '',
})

const rules = reactive<FormRules<RuleForm>>({
const formLabelWidth = '100px'
const RuleFormLabelWidth = '90px'
const optionAddress = ref([])
const optionType = ref([])
const state = ref()
const removeId = ref([])

interface RuleForm {
    sampleCode: string
    sampleTypeName: number
    idCard: string
    sourceName: string
    sex: number
    age: number
    telephone: string
    homeAddress: string
    receiveDate: string
    collectAddressName: any
    pregnant: number
    remark: string
}
const ruleFormRefAddEdit = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    sampleCode: '',
    sampleTypeName: 106,
    idCard: '',
    sourceName: '',
    sex: 1,
    telephone: '',
    homeAddress: '',
    receiveDate: getCurrentDate(),
    collectAddressName: null,
    age: 0,
    pregnant: 0,
    remark: '',
})

const rules = reactive<FormRules<RuleForm>>({
    sampleCode: [
        { required: true, message: '不能为空', trigger: 'blur' },
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    sampleTypeName: [
        { required: true, message: '不能为空', trigger: 'blur' },
    sampleTypeName: [
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    idCard: [
        { required: true, message: '不能为空', trigger: 'blur' },
        {
            pattern: /^\d{15}(\d{3})?$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
        }
        { required: true, message: '不能为空', trigger: 'blur' },
        {
            pattern: /^\d{15}(\d{3})?$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
        }
    ],
    sourceName: [
        { required: true, message: '不能为空', trigger: 'blur' },
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '选择性别', trigger: 'blur' },
        { required: true, message: '选择性别', trigger: 'blur' },
    ],
    age: [
        { required: true, message: '输入年龄', trigger: 'blur' },
        { required: true, message: '输入年龄', trigger: 'blur' },
    ],
    receiveDate: [
        { required: true, message: '不能为空', trigger: 'blur' },
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    collectAddressName: [
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    pregnant: [
        { required: true, message: '选择是否怀孕', trigger: 'blur' },
    ],
})

onMounted(() => {
    getList()
    getAddress()
    getType()
})

function handleChangeAddress(val) {
    console.log(val);
    console.log(ruleForm.collectAddressName)
}
// 获取当前时间
function getCurrentDate(): string {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
// 包括hours, minutes, seconds
// padStart(2, '0')  是为了保证即使是个位数也能显示为两位（例如 9 变成 09）。
function getCurrentDateHours(): string {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const hours = String(today.getHours()).padStart(2, '0');
    const minutes = String(today.getMinutes()).padStart(2, '0');
    const seconds = String(today.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 获取列表
const getList = () => {
    getSampesList(form).then(res => {
        console.log(res)
    getList()
    getAddress()
    getType()
})

function handleChangeAddress(val) {
    console.log(val);
    console.log(ruleForm.collectAddressName)
}
// 获取当前时间
function getCurrentDate(): string {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
// 包括hours, minutes, seconds
// padStart(2, '0')  是为了保证即使是个位数也能显示为两位（例如 9 变成 09）。
function getCurrentDateHours(): string {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const hours = String(today.getHours()).padStart(2, '0');
    const minutes = String(today.getMinutes()).padStart(2, '0');
    const seconds = String(today.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 获取列表
const getList = () => {
    getSampesList(form).then(res => {
        console.log(res)
        tableData.value = res.page.list
        total.value = res.page.totalCount
    })
}
// 获取采集地点
function getAddress() {
    getSampesAddress().then(res => {
        console.log(res, '采集地点');
        optionAddress.value = res.items
    })
}
// 获取样本类型
function getType() {
    getSampesType().then(res => {
        console.log(res, '样本类型');
        optionType.value = res.list
    })
}

// 编辑
const donorsInfoId = ref()
const samplesId = ref()
function editSamples(val: any) {
    remk.value = false
    getSampletype(ruleForm.sampleTypeName).then(res => {
        sampleType.value = res.sampleType
    })
    getIdSamples(val, { t }).then(res => {
        dialogFormVisibleAddUp.value = true
        donorsInfoId.value = res.response.donorsInfo
        samplesId.value = res.response.samples
        ruleForm.sampleCode = res.response.samples.sampleCode
        ruleForm.sampleTypeName = res.response.samples.sampleTypeName
        ruleForm.idCard = res.response.samples.sourceIdCard
        ruleForm.sourceName = res.response.donorsInfo.name
        ruleForm.sex = res.response.donorsInfo.sex
        ruleForm.age = res.response.donorsInfo.sex
        ruleForm.telephone = res.response.donorsInfo.telephone
        ruleForm.homeAddress = res.response.donorsInfo.homeAddress
        ruleForm.pregnant = res.response.samples.pregnant
        ruleForm.receiveDate = res.response.samples.receiveDate
        ruleForm.remark = res.response.samples.remark
    })
}
// 多选
const handleSelectionChange = (val: any) => {
    delId.value = []
    let result = val.some(function (item, index) {
        return item.status == 0
    })
    state.value = result
    if (result) {
        for (const item of val) {
            delId.value.push(item.id)
        }
    }
    removeId.value = []
    for (const item of val) {
        if (item.state == 1) {
            removeId.value.push(item.id)
        }
    }
}
// 分页
// 切换条数
function handleSizeChange(val: number) {
    pageSize.value = val
    form.limit = val
    getList()
}

function handlePageChange(val: number) {
    currentPage.value = val
    form.page = val
    getList()
}

// 查询
function search() {
    form.page = 1
    getList()
}
//高级查询
function advancedSearch() {
    reset()
    dialogFormVisible.value = true
}
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            getList()
            dialogFormVisible.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    reset()
    dialogFormVisible.value = false
}

// 重置查询
function resetSearch() {
    reset()
    form.key = null
    getList()
}
// 重置
function reset() {
    form.sampleCode = ''
    form.sampleTypeName = ''
    form.collectAddressName = ''
    form.receiveDateStart = ''
    form.receiveDateEnd = ''
    form.createOnStart = ''
    form.createOnEnd = ''
    form.ageStart = ''
    form.ageEnd = ''
    form.state = ''
    form.sex = ''
    form.sourceName = ''
    form.sourceIdCard = ''
    form.telephone = ''
    form.page = 1
    form.limit = 10
}
//录入/修改
const remk = ref(false)
function log() {
    remk.value = true
    dialogFormVisibleAddUp.value = true
    nextTick(() => {
        ruleFormRefAddEdit.value?.resetFields()
    })
    ruleForm.sampleCode = ''
    ruleForm.idCard = ''
    ruleForm.sourceName = ''
    ruleForm.sex = 1
    ruleForm.age = 0
    ruleForm.telephone = ''
    ruleForm.homeAddress = ''
    ruleForm.pregnant = 0
    ruleForm.receiveDate = ''
    ruleForm.remark = ''
    getSampesByCreator().then(res => {
        console.log(res);
    })
    getSampletype(ruleForm.sampleTypeName).then(res => {
        sampleType.value = res.sampleType
    })
}
function getIdCard() {
    getIdCardDetail(ruleForm.idCard).then(res => {
        if (res.donorsInfo) {
            donorsInfo.value = res.donorsInfo
            ruleForm.sourceName = res.donorsInfo.name
            ruleForm.sex = res.donorsInfo.sex
            ruleForm.age = res.donorsInfo.age
            ruleForm.telephone = res.donorsInfo.telephone
            ruleForm.homeAddress = res.donorsInfo.homeAddress
        }
    })
}
function getSample(val: any) {
    getSampletype(val).then(res => {
        console.log(res, '521');
        sampleType.value = res.sampleType
    })
}
const sampleType = ref({})
const donorsInfo = ref({})

const submitFormAddAndEdit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
function getSample(val: any) {
    getSampletype(val).then(res => {
        console.log(res, '521');
        sampleType.value = res.sampleType
    })
}
const sampleType = ref({})
const donorsInfo = ref({})

const submitFormAddAndEdit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (remk.value) {
                let data = {
                    t,
                    donorsInfo: {
                        age: ruleForm.age,
                        homeAddress: ruleForm.homeAddress,
                        idCard: ruleForm.idCard,
                        name: ruleForm.sourceName,
                        sampleCode: ruleForm.sampleCode,
                        sex: ruleForm.sex,
                        telephone: ruleForm.telephone,
                    },
                    samples: {
                        collectAddress: ruleForm.collectAddressName.id,
                        collectAddressName: ruleForm.collectAddressName.itemName,
                        name: sampleType.value.name + ' | ' + ruleForm.sampleCode,
                        pregnant: ruleForm.pregnant,
                        remark: ruleForm.remark,
                        sampleCode: ruleForm.sampleCode,
                        sampleType: sampleType.value.id,
                        sampleTypeName: sampleType.value.name,
                        sourceIdCard: ruleForm.idCard,
                        receiveDate: ruleForm.receiveDate
                    },
                }
                saveSamples(data).then(res => {
                    dialogFormVisibleAddUp.value = false
                    ElMessage({
                        type: 'success',
                        message: `操作成功`
                    })
                    getList()
            if (remk.value) {
                let data = {
                    t,
                    donorsInfo: {
                        age: ruleForm.age,
                        homeAddress: ruleForm.homeAddress,
                        idCard: ruleForm.idCard,
                        name: ruleForm.sourceName,
                        sampleCode: ruleForm.sampleCode,
                        sex: ruleForm.sex,
                        telephone: ruleForm.telephone,
                    },
                    samples: {
                        collectAddress: ruleForm.collectAddressName.id,
                        collectAddressName: ruleForm.collectAddressName.itemName,
                        name: sampleType.value.name + ' | ' + ruleForm.sampleCode,
                        pregnant: ruleForm.pregnant,
                        remark: ruleForm.remark,
                        sampleCode: ruleForm.sampleCode,
                        sampleType: sampleType.value.id,
                        sampleTypeName: sampleType.value.name,
                        sourceIdCard: ruleForm.idCard,
                        receiveDate: ruleForm.receiveDate
                    },
                }
                saveSamples(data).then(res => {
                    dialogFormVisibleAddUp.value = false
                    ElMessage({
                        type: 'success',
                        message: `操作成功`
                    })
                    getList()
                })
            } else {
                donorsInfoId.value.age = ruleForm.age
                donorsInfoId.value.homeAddress = ruleForm.homeAddress
                donorsInfoId.value.idCard = ruleForm.idCard
                donorsInfoId.value.name = ruleForm.sourceName
                donorsInfoId.value.sampleCode = ruleForm.sampleCode
                donorsInfoId.value.sex = ruleForm.sex
                donorsInfoId.value.telephone = ruleForm.telephone
                samplesId.value.collectAddress = ruleForm.collectAddressName.id
                samplesId.value.collectAddressName = ruleForm.collectAddressName.itemName
                samplesId.value.name = sampleType.value.name + ' | ' + ruleForm.sampleCode
                samplesId.value.pregnant = ruleForm.pregnant
                samplesId.value.remark = ruleForm.remark
                samplesId.value.sampleCode = ruleForm.sampleCode
                samplesId.value.sampleType = sampleType.value.id
                samplesId.value.sampleTypeName = sampleType.value.name
                samplesId.value.sourceIdCard = ruleForm.idCard
                samplesId.value.receiveDate = ruleForm.receiveDate
                let data = {
                    t,
                    donorsInfo: { ...donorsInfoId.value },
                    samples: { ...samplesId.value },
                }
                saveSamples(data).then(res => {
                    dialogFormVisibleAddUp.value = false
                    ElMessage({
                        type: 'success',
                        message: `操作成功`
                    })
                    ruleForm.sampleTypeName = 106
                    getList()
                donorsInfoId.value.age = ruleForm.age
                donorsInfoId.value.homeAddress = ruleForm.homeAddress
                donorsInfoId.value.idCard = ruleForm.idCard
                donorsInfoId.value.name = ruleForm.sourceName
                donorsInfoId.value.sampleCode = ruleForm.sampleCode
                donorsInfoId.value.sex = ruleForm.sex
                donorsInfoId.value.telephone = ruleForm.telephone
                samplesId.value.collectAddress = ruleForm.collectAddressName.id
                samplesId.value.collectAddressName = ruleForm.collectAddressName.itemName
                samplesId.value.name = sampleType.value.name + ' | ' + ruleForm.sampleCode
                samplesId.value.pregnant = ruleForm.pregnant
                samplesId.value.remark = ruleForm.remark
                samplesId.value.sampleCode = ruleForm.sampleCode
                samplesId.value.sampleType = sampleType.value.id
                samplesId.value.sampleTypeName = sampleType.value.name
                samplesId.value.sourceIdCard = ruleForm.idCard
                samplesId.value.receiveDate = ruleForm.receiveDate
                let data = {
                    t,
                    donorsInfo: { ...donorsInfoId.value },
                    samples: { ...samplesId.value },
                }
                saveSamples(data).then(res => {
                    dialogFormVisibleAddUp.value = false
                    ElMessage({
                        type: 'success',
                        message: `操作成功`
                    })
                    ruleForm.sampleTypeName = 106
                    getList()
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetFormAddAndUpdate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisibleAddUp.value = false
}
// 未审
function underReview(val: any) {
    let delTask = val ? val : delId.value
    let actionText = val ? '审核入库' : '批量审核入库'
    const taskIds = Array.isArray(delTask) ? delTask : [delTask]
    ElMessageBox.confirm(
        `确定对[id=${taskIds.join(',')}]进行[${actionText}]操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return getSampesReview(taskIds).then(res => {
            ElMessage({
                type: 'success',
                message: `审核成功,(` + res.operCnt + `)个`
            })
            form.page = 1
            getList()
        })
    })
}
// 删除
function deleteSamples(val: any) {
    ElMessageBox.confirm(
        `确定对[id=${val}]进行[删除]操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return sampeswDelete([val]).then(res => {
            ElMessage({
                type: 'success',
                message: `操作成功`,
            })
            form.page = 1
            getList()
        }).catch(err => {
            console.error('删除失败:', err)
            ElMessage({
                type: 'error',
                message: '删除失败: ' + err.message,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '操作已取消',
        })
    })
}

// 出库
function stockRemove() {
    ElMessageBox.confirm(
        `确定对[id=${removeId.value}进行批量出库操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return sampesRemove(removeId.value).then(res => {
            console.log(res, 12);
            ElMessage({
                type: 'success',
                message: `出库成功,(` + res.operCnt + ')个',
            })
            form.page = 1
            getList()
        }).catch(err => {
            console.error('删除失败:', err)
            ElMessage({
                type: 'error',
                message: '删除失败: ' + err.message,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '操作已取消',
        })
    })
}
// 导出
function exportXlsx() {
    exportSamples(form).then(res => {
        // console.log(res, '成功');
        // 创建一个blob对象 存储excel文件数据
        let blob = new Blob([res])
        const link = document.createElement('a')
        //创建一个下载链接  并将其赋值给href   
        link.href = window.URL.createObjectURL(blob)
        link.target = '_blank'
        //设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `样本采集${nowTime.getTime()}.xlsx`)
        //将a标签添加到页面上
        document.body.appendChild(link)
        //触发点击事件
        link.click()
        //移出a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err);
        })
            console.log('error submit!', fields)
        }
    })
}

const resetFormAddAndUpdate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisibleAddUp.value = false
}
// 未审
function underReview(val: any) {
    let delTask = val ? val : delId.value
    let actionText = val ? '审核入库' : '批量审核入库'
    const taskIds = Array.isArray(delTask) ? delTask : [delTask]
    ElMessageBox.confirm(
        `确定对[id=${taskIds.join(',')}]进行[${actionText}]操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return getSampesReview(taskIds).then(res => {
            ElMessage({
                type: 'success',
                message: `审核成功,(` + res.operCnt + `)个`
            })
            form.page = 1
            getList()
        })
    })
}
// 删除
function deleteSamples(val: any) {
    ElMessageBox.confirm(
        `确定对[id=${val}]进行[删除]操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return sampeswDelete([val]).then(res => {
            ElMessage({
                type: 'success',
                message: `操作成功`,
            })
            form.page = 1
            getList()
        }).catch(err => {
            console.error('删除失败:', err)
            ElMessage({
                type: 'error',
                message: '删除失败: ' + err.message,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '操作已取消',
        })
    })
}

// 出库
function stockRemove() {
    ElMessageBox.confirm(
        `确定对[id=${removeId.value}进行批量出库操作?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return sampesRemove(removeId.value).then(res => {
            console.log(res, 12);
            ElMessage({
                type: 'success',
                message: `出库成功,(` + res.operCnt + ')个',
            })
            form.page = 1
            getList()
        }).catch(err => {
            console.error('删除失败:', err)
            ElMessage({
                type: 'error',
                message: '删除失败: ' + err.message,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '操作已取消',
        })
    })
}
// 导出
function exportXlsx() {
    exportSamples(form).then(res => {
        // console.log(res, '成功');
        // 创建一个blob对象 存储excel文件数据
        let blob = new Blob([res])
        const link = document.createElement('a')
        //创建一个下载链接  并将其赋值给href   
        link.href = window.URL.createObjectURL(blob)
        link.target = '_blank'
        //设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `样本采集${nowTime.getTime()}.xlsx`)
        //将a标签添加到页面上
        document.body.appendChild(link)
        //触发点击事件
        link.click()
        //移出a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err);
        })
}
</script>

<style scoped>
.samples {
    padding: 10px;
    box-sizing: border-box;
}

.radius {
    border: 1px solid var(--el-border-color);
    background-color: var(--el-bg-color);
    color: var(--el-text-color-primary);
    padding: 20px;
}

.samples-header .el-form-item {
    margin-right: 10px;
}

.table-container {
    margin-top: 20px;
}

:deep(.cell) {
    text-align: center;
    padding: 0px 10px;
}

.example-showcase .el-dropdown+.el-dropdown {
    margin-left: 15px;
<style scoped>
.samples {
    padding: 10px;
    box-sizing: border-box;
}

.radius {
    border: 1px solid var(--el-border-color);
    background-color: var(--el-bg-color);
    color: var(--el-text-color-primary);
    padding: 20px;
}

.samples-header .el-form-item {
    margin-right: 10px;
}

.table-container {
    margin-top: 20px;
}

:deep(.cell) {
    text-align: center;
    padding: 0px 10px;
}

.example-showcase .el-dropdown+.el-dropdown {
    margin-left: 15px;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

:deep(.submit .el-form-item__content) {
    display: flex;
    justify-content: flex-end
}

:deep(.receiveDate .el-input__wrapper) {
    width: 100%;
:deep(.submit .el-form-item__content) {
    display: flex;
    justify-content: flex-end
}

:deep(.receiveDate .el-input__wrapper) {
    width: 100%;
}
</style>